<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title>完善当当购物车页面</title>
    <link type="text/css" rel="stylesheet" href="css/cartStyle.css" />
</head>

<body>

    <div class="content">
        <div class="logo">
            <img src="images/DM_20240927095008_001.jpg"><span onclick="close_plan();">关闭</span>
        </div>
        <div class="cartList">
            <ul>
                <li>
                    <p onclick="collection();">移入收藏</p>
                    <p onclick="del();">删除</p>
                </li>
                <li id="price0">¥159.00</li>
                <li><input type="button" name="minus" value="-" onclick="minus(0);"><input type="text" name="amount"
                        value="1"><input type="button" name="plus" value="+" onclick="plus(0);"></li>
                <li>¥<input type="text" name="price" value="159.00"></li>
            </ul>
            <ul>
                <li>
                    <p onclick="collection();">移入收藏</p>
                    <p onclick="del();">删除</p>
                </li>
                <li id="price1">¥159.00</li>
                <li><input type="button" name="minus" value="-" onclick="minus(1);"><input type="text" name="amount"
                        value="1"><input type="button" name="plus" value="+" onclick="plus(1);"></li>
                <li>¥<input type="text" name="price" value="159.00"></li>
            </ul>
            <ol>
                <li id="totalPrice">&nbsp;</li>
                <li><span onclick="accounts();">结 算</span></li>
            </ol>
        </div>
    </div>
    <script>
        function minus(num) {
            let amount = document.getElementsByName("amount")[num];
            let count = parseInt(amount.value) - 1;
            if (count >= 1) {
                amount.value = count;
                updatePrice(num, count);
            }
        }

        function plus(num) {
            let amount = document.getElementsByName("amount")[num];
            let count = parseInt(amount.value) + 1;
            amount.value = count;
            updatePrice(num, count);
        }

        function updatePrice(index, count) {
            let priceInput = document.getElementsByName("price")[index];
            let unitPrice = parseFloat(priceInput.value);
            let totalPrice = unitPrice * count;
            priceInput.value = totalPrice.toFixed(2);
            sum();
        }

        function sum() {
            let amounts = document.getElementsByName("amount");
            let prices = document.getElementsByName("price");
            let total = 0;
            for (let i = 0; i < amounts.length; i++) {
                total += parseFloat(amounts[i].value) * parseFloat(prices[i].value);
            }
            document.getElementById("totalPrice").innerHTML = "¥" + total.toFixed(2);
        }

        // 初始化总价格
        sum();
    </script>
</body>

</html>